<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="description" content="聊天交友平台是一款在线聊天网站，提供了在线交友、世界聊天、随机聊天、离线信息以及游戏娱乐功能，大家可以在这里找到许多欢乐。">
    <meta name="keywords" content="网站在线聊天，聊天交友平台，不坠青云之志，thenie，随机聊天，在线交友，认识新朋友，小游戏，娱乐，放松，交友，简便，快捷">
    <title>(｡・`ω´･) 世界之窗</title>

    <!--图标库-->
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css'>

    <!-- 默认样式-->
    <link rel="stylesheet" th:href="@{/world/css/reset.min.css}">

    <!-- 主要样式-->
    <link rel="stylesheet" th:href="@{/world/css/style.css}">

</head>
<body>

<div class="container clearfix">
    <div class="people-list" id="people-list">
        <div class="search">
            当前用户在线列表
        </div>
        <ul class="list">
            <li class="clearfix">
                <img th:src="@{${user.photo}}" alt="avatar">
                <div class="about" th:id="${user.id}">
                    <div class="name" th:text="${user.realName}"></div>
                    <div class="status">
                        <i class="fa fa-circle online"></i> <span th:text="${user.status}"></span>
                    </div>
                </div>
            </li>
            <li th:each="worldUser : ${worldUserList}"  class="clearfix">
                <img th:src="@{${worldUser.photo}}" alt="avatar">
                <div class="about" th:id="${worldUser.id}">
                    <div class="name" th:text="${worldUser.realName}"></div>
                    <div class="status">
                        <i class="fa fa-circle online"></i> <span th:text="${worldUser.status}"></span>
                    </div>
                </div>
            </li>

        </ul>
    </div>

    <div class="chat">
        <div class="chat-header clearfix">
            <img th:src="@{/world/img/world-title.png}" alt="avatar"/>

            <div class="chat-about">
                <div class="chat-with">小世界之窗</div>
                <div class="chat-num-messages">在这里畅所欲言，认识你的新朋友吧~~~</div>
            </div>
            <i class="fa fa-star"></i>
        </div> <!-- end chat-header -->

        <div class="chat-history">
            <ul>
            </ul>

        </div> <!-- end chat-history -->

        <div class="chat-message clearfix">
            <textarea name="message-to-send" id="message-to-send" placeholder="输入消息，一点即达..." rows="3"></textarea>

                    <i class="fa fa-smile-o"></i>


            <button>发送</button>

        </div> <!-- end chat-message -->

    </div> <!-- end chat -->

</div> <!-- end container -->

<script id="message-template" type="text/x-handlebars-template">
    <li class="clearfix">
        <div class="message-data align-right">
            <span class="message-data-time">{{time}}</span> &nbsp; &nbsp;
            <span class="message-data-name">{{name}}</span> <img src="{{photo}}"/>
        </div>
        <div class="message other-message float-right">
            {{messageOutput}}
        </div>
    </li>
</script>

<script id="message-response-template" type="text/x-handlebars-template">
    <li>
        <div class="message-data">
            <img src="{{photo}}"/><span class="message-data-name">{{name}}</span>
            <span class="message-data-time">{{time}}</span>
        </div>
        <div class="message my-message">
            {{response}}
        </div>
    </li>
</script>

<script type="text/javascript" th:src="@{/world/js/jquery.min.js}"></script>
<script type="text/javascript" th:src="@{/world/js/handlebars.min.js}"></script>
<script type="text/javascript" th:src="@{/world/js/list.min.js}"></script>

<script th:inline="javascript">

    //自己的用户信息
    var user = /*[[${user}]]*/ {};
    //webSocket长链接
    var webSocket = null;

    var host = window.location.host;
    if ('WebSocket' in window) {
        webSocket = new WebSocket("ws://" + host + "/ws/world/dialog?userId=" + user.id);
    } else {
        alert('当前浏览器不支持 websocket，可能会导致部分功能不可用')
    }

    /**
     * websocket的四种事件
     */
    webSocket.onerror = function () {//出错执行
        layer.msg("WebSocket连接发生错误");
    };
    webSocket.onopen = function () {//连接成功后的回调方法
    }
    webSocket.onmessage = function (event) {//收到消息后的处理方法

        // var message = JSON.parse(event.data);
        var resp = JSON.parse(event.data);
        console.log("resp:" + resp);

        if (resp.code === 5){//有用户进入聊天室
            addOnlineList(resp.obj.user)
        }else if (resp.code === 1){//有用户发送消息
            chat.receiveMessage(resp.obj);
        }else if (resp.code === 6){//有用户下线
            removeOnlineList(resp.obj)
        }

    }
    //监听窗口关闭事件
    window.onbeforeunload = function () {
        // 主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常
        webSocket.close();

    }
    webSocket.onclose = function () {//连接关闭后的方法
        console.log("链接关闭");
    }

    var chat = {
        //消息内容
        messageToSend: '',
        //消息返回消息集合
        messageResponses: [
            'Why did the web developer leave the restaurant? Because of the table layout.',
            'How do you comfort a JavaScript bug? You console it.',
            'An SQL query enters a bar, approaches two tables and asks: "May I join you?"',
            'What is the most used language in programming? Profanity.',
            'What is the object-oriented way to become wealthy? Inheritance.',
            'An SEO expert walks into a bar, bars, pub, tavern, public house, Irish pub, drinks, beer, alcohol'
        ],
        //初始化
        init: function () {
            this.cacheDOM();
            this.bindEvents();
            this.render();
        },
        //属性缓存
        cacheDOM: function () {
            this.$chatHistory = $('.chat-history');
            this.$button = $('button');
            this.$textarea = $('#message-to-send');
            this.$chatHistoryList = this.$chatHistory.find('ul');
        },
        //事件监听
        bindEvents: function () {
            this.$button.on('click', this.addMessage.bind(this));
            this.$textarea.on('keyup', this.addMessageEnter.bind(this));
        },
        //呈现消息实现方法
        render: function () {
            this.scrollToBottom();
            if (this.messageToSend.trim() !== '') {
                //发送消息
                sendMsg(this.messageToSend);
                // 发送消息展示模板
                var template = Handlebars.compile($("#message-template").html());
                var context = {
                    messageOutput: this.messageToSend,
                    time: this.getCurrentTime(),
                    name: user.realName,
                    photo: user.photo
                };

                this.$chatHistoryList.append(template(context));
                this.scrollToBottom();
                this.$textarea.val('');
            }

        },
        receiveMessage: function(obj){
            // 返回消息模板
            var templateResponse = Handlebars.compile($("#message-response-template").html());
            var contextResponse = {
                response: obj.text,
                time: this.getCurrentTime(),
                name: obj.user.realName,
                photo: obj.user.photo
            };

            this.$chatHistoryList.append(templateResponse(contextResponse));
            this.scrollToBottom();
        },
        //添加消息
        addMessage: function () {
            this.messageToSend = this.$textarea.val()
            this.render();
        },
        //按键消息监听
        addMessageEnter: function (event) {
            // enter was pressed
            if (event.keyCode === 13) {
                this.addMessage();
            }
        },
        //滚动按钮到底部
        scrollToBottom: function () {
            this.$chatHistory.scrollTop(this.$chatHistory[0].scrollHeight);
        },
        //返回当前时间
        getCurrentTime: function () {
            var date = new Date();
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var up = "上午";
            if (hours >= 12) {
                up = "下午";
                if (hours > 12) {
                    hours -= 12;
                }
            }
            if (minutes<10){
                minutes= "0"+minutes;
            }
            return up+" "+hours + ":" + minutes;
        },
        //返回随机一项
        getRandomItem: function (arr) {
            return arr[Math.floor(Math.random() * arr.length)];
        }

    };

    //聊天初始化
    chat.init();

    //搜索监听
    var searchFilter = {
        options: {valueNames: ['name']},
        init: function () {
            var userList = new List('people-list', this.options);
            var noItems = $('<li id="no-items-found">No items found</li>');

            userList.on('updated', function (list) {
                if (list.matchingItems.length === 0) {
                    $(list.list).append(noItems);
                } else {
                    noItems.detach();
                }
            });
        }
    };

    //搜索初始化
    searchFilter.init();

    /*用户上线—添加List*/
    function addOnlineList(curUser) {
        if (curUser != null){
            var str =
                "            <li  class=\"clearfix\">\n" +
                "                <img src='"+curUser.photo+"' alt=\"avatar\"/>\n" +
                "                <div class=\"about\" id='"+curUser.id+"'>\n" +
                "                    <div class=\"name\">"+curUser.realName+"</div>\n" +
                "                    <div class=\"status\">\n" +
                "                        <i class=\"fa fa-circle online\"></i> "+curUser.status+"\n" +
                "                    </div>\n" +
                "                </div>\n" +
                "            </li>";
            $(".list").append(str);
        }
    }
    /*用户下线—清除List*/
    function removeOnlineList(id) {
        let $list_user = $('#'+id);
        if ($list_user != null){
            $list_user.parent().remove();
        }
    }
    /*发送消息*/
    function sendMsg(text) {
        if (text!=null && text!=='')
        webSocket.send(text);
    }

</script>

</body>
</html>